package com.videoaggre.zcl.ui.fragment.agefans

import android.os.Bundle
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.view.View
import androidx.fragment.app.viewModels
import com.videoaggre.zcl.R
import com.videoaggre.zcl.common.changeVisibility
import com.videoaggre.zcl.common.textSpan
import com.videoaggre.zcl.ui.activity.agefans.AgefansDetailsActivity
import com.videoaggre.zcl.ui.activity.agefans.AgefansDetailsDescAdapter
import com.videoaggre.zcl.ui.fragment.BaseFragment
import com.videoaggre.zcl.ui.viewmodel.AgefansDetailsViewModel
import com.videoaggre.zcl.utils.FullyLinearLayoutManager
import com.videoaggre.zcl.utils.GlideUtils
import kotlinx.android.synthetic.main.agefans_fragment_detail_info.*

/**
 * 动漫信息
 */
class AgefansDetailInfoFragment : BaseFragment(R.layout.agefans_fragment_detail_info) {
    private val mAgefansDetailsViewModel: AgefansDetailsViewModel by viewModels({ requireActivity() })
    private val mAgefansDetailsDescAdapter: AgefansDetailsDescAdapter = AgefansDetailsDescAdapter()
    override fun initView(rootView: View?, savedInstanceState: Bundle?) {
        rvDesc.layoutManager = FullyLinearLayoutManager(context)
        rvDesc.adapter = mAgefansDetailsDescAdapter
    }

    override fun initData(rootView: View?, savedInstanceState: Bundle?) {
        mAgefansDetailsViewModel.mAgefansDetailsLiveData.observe(this) {
            GlideUtils.intoView(this, it.cover, ivCover)
            mAgefansDetailsDescAdapter.datas = it.tags
            mAgefansDetailsDescAdapter.notifyDataSetChanged()
            groupRelates.changeVisibility = it.relatesSeries.isNotEmpty()
            if (it.relatesSeries.isNotEmpty()) {
                tvRelates.movementMethod = LinkMovementMethod.getInstance();
                val relatesSeriesText = StringBuilder()
                tvRelates.textSpan("textSpan") {
                    it.relatesSeries.forEach { agefansItem ->
                        relatesSeriesText.append(agefansItem.name).append("\n")
                        spanText = agefansItem.name
                        addUnderlineSpan()
                        addClickableSpan(object : ClickableSpan() {
                            override fun onClick(widget: View) = AgefansDetailsActivity.open(widget.context, agefansItem.link)
                        })
                    }
                    relatesSeriesText.deleteCharAt(relatesSeriesText.length - 1)
                    text = relatesSeriesText.toString()
                }
            }
        }
    }
}